<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.1.2">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.1.2">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.2" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="分类（class）与聚类（cluster）不同，分类是有监督学习模型，聚类属于无监督学习模型。聚类讲究使用一些算法把样本划分为n个群落。一般情况下，这种算法都需要计算欧氏距离。">
<meta name="keywords" content="AI进阶,机器学习">
<meta property="og:type" content="article">
<meta property="og:title" content="机器学习-聚类问题">
<meta property="og:url" content="https://rencheng.cc/2019/03/01/ml/聚类/index.html">
<meta property="og:site_name" content="PHOENIX&#39;s Blog">
<meta property="og:description" content="分类（class）与聚类（cluster）不同，分类是有监督学习模型，聚类属于无监督学习模型。聚类讲究使用一些算法把样本划分为n个群落。一般情况下，这种算法都需要计算欧氏距离。">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-03-01T07:50:41.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="机器学习-聚类问题">
<meta name="twitter:description" content="分类（class）与聚类（cluster）不同，分类是有监督学习模型，聚类属于无监督学习模型。聚类讲究使用一些算法把样本划分为n个群落。一般情况下，这种算法都需要计算欧氏距离。">



  <link rel="alternate" href="/atom.xml" title="PHOENIX's Blog" type="application/atom+xml">



  
  
  <link rel="canonical" href="https://rencheng.cc/2019/03/01/ml/聚类/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>机器学习-聚类问题 | PHOENIX's Blog</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">PHOENIX's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">Enjoy the journey of life</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://rencheng.cc/2019/03/01/ml/聚类/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="任成">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="PHOENIX's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">机器学习-聚类问题

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-03-01 15:50:41" itemprop="dateCreated datePublished" datetime="2019-03-01T15:50:41+08:00">2019-03-01</time>
            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/教程/" itemprop="url" rel="index"><span itemprop="name">教程</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                <span title="本文字数">8.9k</span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>分类（class）与聚类（cluster）不同，分类是有监督学习模型，聚类属于无监督学习模型。聚类讲究使用一些算法把样本划分为n个群落。一般情况下，这种算法都需要计算欧氏距离。<br><a id="more"></a></p>
<h2 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h2><p>在输出未知的前提下，仅根据已知的输入寻找样本之间的内在联系，据此将输入样本划分为不同的族群。</p>
<h2 id="量化相似度"><a href="#量化相似度" class="headerlink" title="量化相似度"></a>量化相似度</h2><h3 id="欧式距离"><a href="#欧式距离" class="headerlink" title="欧式距离"></a>欧式距离</h3><p>$P(x1,y1)$<br>$Q(x2,y2)$<br>$|PQ|=\sqrt{(x1 - x2)^2 + (y1 - y2)^2}$</p>
<p>$P(x1,y1,z1)$<br>$Q(x2,y2,z2)$<br>$|PQ|=\sqrt{(x1-x2)^2+(y1-y2)^2+(z1-z2)^2}$</p>
<p>$P(x1,y1,z1,…)$<br>$Q(x2,y2,z2,…)$</p>
<p>张三(1.7,60)<br>李四(1.75,200)<br>王五(2.5,65)<br>赵六(1.72,61)<br>两个N维样本之间的欧氏距离越小，就越相似，反而反之。</p>
<p>用两个样本对应特征值之差的平方和之平方根，即欧氏距离，来表示这两个样本的相似性。</p>
<h2 id="K均值聚类"><a href="#K均值聚类" class="headerlink" title="K均值聚类"></a>K均值聚类</h2><p>第一步：随机选择k个样本作为k个聚类的中心，计算每个样本到各个聚类中心的欧氏距离，将该样本分配到与之距离最近的聚类中心所在的类别中。</p>
<p>第二步：根据第一步所得到的聚类划分，分别计算每个聚类的几何中心，将几何中心作为新的聚类中心，重复第一步，直到计算所得几何中心与聚类中心重合或接近重合为止。</p>
<p><strong>注意：</strong></p>
<ol>
<li>聚类数k必须事先已知。借助某些评估指标，优选最好的聚类数。</li>
<li>聚类中心的初始选择会影响到最终聚类划分的结果。初始中心尽量选择距离较远的样本。</li>
</ol>
<p>K均值算法相关API：<br><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> sklearn.cluster <span class="keyword">as</span> sc</span><br><span class="line"><span class="comment"># n_clusters: 聚类数</span></span><br><span class="line">model = sc.KMeans(n_clusters=<span class="number">4</span>)</span><br><span class="line"><span class="comment"># 不断调整聚类中心，知道最终聚类中心稳定则聚类完成</span></span><br><span class="line">model.fit(x)</span><br><span class="line"><span class="comment"># 获取训练结果的聚类中心</span></span><br><span class="line">centers = model.cluster_centers_</span><br><span class="line">``` </span><br><span class="line">案例：加载multiple3.txt，基于K均值算法完成样本的聚类。</span><br><span class="line">``` py</span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.cluster <span class="keyword">as</span> sc</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x = []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/multiple3.txt'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data = [float(substr) <span class="keyword">for</span> substr</span><br><span class="line">			<span class="keyword">in</span> line.split(<span class="string">','</span>)]</span><br><span class="line">		x.append(data)</span><br><span class="line">x = np.array(x)</span><br><span class="line"><span class="comment"># K均值聚类器</span></span><br><span class="line">model = sc.KMeans(n_clusters=<span class="number">4</span>)</span><br><span class="line">model.fit(x)</span><br><span class="line">centers = model.cluster_centers_ <span class="comment"># 聚类中心</span></span><br><span class="line">l, r, h = x[:, <span class="number">0</span>].min() - <span class="number">1</span>, x[:, <span class="number">0</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">b, t, v = x[:, <span class="number">1</span>].min() - <span class="number">1</span>, x[:, <span class="number">1</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">grid_x = np.meshgrid(np.arange(l, r, h),</span><br><span class="line">	np.arange(b, t, v))</span><br><span class="line">flat_x = np.c_[grid_x[<span class="number">0</span>].ravel(), grid_x[<span class="number">1</span>].ravel()]</span><br><span class="line">flat_y = model.predict(flat_x)</span><br><span class="line">grid_y = flat_y.reshape(grid_x[<span class="number">0</span>].shape)</span><br><span class="line">mp.figure(<span class="string">'K-Means'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'K-Means'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.pcolormesh(grid_x[<span class="number">0</span>], grid_x[<span class="number">1</span>], grid_y, cmap=<span class="string">'gray'</span>)</span><br><span class="line">mp.scatter(x[:, <span class="number">0</span>], x[:, <span class="number">1</span>], c=model.labels_,</span><br><span class="line">	cmap=<span class="string">'brg'</span>, s=<span class="number">80</span>)</span><br><span class="line">mp.scatter(centers[:, <span class="number">0</span>], centers[:, <span class="number">1</span>],</span><br><span class="line">	marker=<span class="string">'+'</span>, c=<span class="string">'gold'</span>, s=<span class="number">1000</span>, linewidth=<span class="number">1</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure></p>
<p>图像预处理之颜色量化</p>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> scipy.misc <span class="keyword">as</span> sm</span><br><span class="line"><span class="keyword">import</span> sklearn.cluster <span class="keyword">as</span> sc</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">image = sm.imread(<span class="string">'../data/lily.jpg'</span>,</span><br><span class="line">	<span class="literal">True</span>).astype(np.uint8)</span><br><span class="line">x = image.reshape(<span class="number">-1</span>, <span class="number">1</span>)</span><br><span class="line">model = sc.KMeans(n_clusters=<span class="number">4</span>)</span><br><span class="line">model.fit(x)</span><br><span class="line">y = model.labels_</span><br><span class="line">centers = model.cluster_centers_.squeeze()</span><br><span class="line">z = centers[y]</span><br><span class="line">image4 = z.reshape(image.shape)</span><br><span class="line">model = sc.KMeans(n_clusters=<span class="number">3</span>)</span><br><span class="line">model.fit(x)</span><br><span class="line">y = model.labels_</span><br><span class="line">centers = model.cluster_centers_.squeeze()</span><br><span class="line">z = centers[y]</span><br><span class="line">image3 = z.reshape(image.shape)</span><br><span class="line">model = sc.KMeans(n_clusters=<span class="number">2</span>)</span><br><span class="line">model.fit(x)</span><br><span class="line">y = model.labels_</span><br><span class="line">centers = model.cluster_centers_.squeeze()</span><br><span class="line">z = centers[y]</span><br><span class="line">image2 = z.reshape(image.shape)</span><br><span class="line">mp.figure(<span class="string">'Image Quantization'</span>,</span><br><span class="line">	facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.subplot(<span class="number">221</span>)</span><br><span class="line">mp.title(<span class="string">'Original'</span>, fontsize=<span class="number">16</span>)</span><br><span class="line">mp.axis(<span class="string">'off'</span>)</span><br><span class="line">mp.imshow(image, cmap=<span class="string">'gray'</span>)</span><br><span class="line">mp.subplot(<span class="number">222</span>)</span><br><span class="line">mp.title(<span class="string">'4 Colors'</span>, fontsize=<span class="number">16</span>)</span><br><span class="line">mp.axis(<span class="string">'off'</span>)</span><br><span class="line">mp.imshow(image4, cmap=<span class="string">'gray'</span>)</span><br><span class="line">mp.subplot(<span class="number">223</span>)</span><br><span class="line">mp.title(<span class="string">'3 Colors'</span>, fontsize=<span class="number">16</span>)</span><br><span class="line">mp.axis(<span class="string">'off'</span>)</span><br><span class="line">mp.imshow(image3, cmap=<span class="string">'gray'</span>)</span><br><span class="line">mp.subplot(<span class="number">224</span>)</span><br><span class="line">mp.title(<span class="string">'2 Colors'</span>, fontsize=<span class="number">16</span>)</span><br><span class="line">mp.axis(<span class="string">'off'</span>)</span><br><span class="line">mp.imshow(image2, cmap=<span class="string">'gray'</span>)</span><br><span class="line">mp.tight_layout()</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<h2 id="均值漂移聚类"><a href="#均值漂移聚类" class="headerlink" title="均值漂移聚类"></a>均值漂移聚类</h2><p>将每个聚类中的样本看作是服从某种概率模型的随机分布，利用已知样本的统计直方图，拟合某个特定的概率模型，以概率密度的峰值点作为相应聚类的中心。然后，根据每个样本与聚类中心的距离，则其近者而从之，完成聚类划分。</p>
<p>1)无需事先给定聚类数<br>2)样本本身从业务上服从某种概率规律</p>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.cluster <span class="keyword">as</span> sc</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x = []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/multiple3.txt'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data = [float(substr) <span class="keyword">for</span> substr</span><br><span class="line">			<span class="keyword">in</span> line.split(<span class="string">','</span>)]</span><br><span class="line">		x.append(data)</span><br><span class="line">x = np.array(x)</span><br><span class="line"><span class="comment"># 均值漂移聚类器</span></span><br><span class="line">bw = sc.estimate_bandwidth(x,</span><br><span class="line">	n_samples=len(x), quantile=<span class="number">0.1</span>)</span><br><span class="line">model = sc.MeanShift(bandwidth=bw,</span><br><span class="line">	bin_seeding=<span class="literal">True</span>)</span><br><span class="line">model.fit(x)</span><br><span class="line">centers = model.cluster_centers_ <span class="comment"># 聚类中心</span></span><br><span class="line">l, r, h = x[:, <span class="number">0</span>].min() - <span class="number">1</span>, x[:, <span class="number">0</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">b, t, v = x[:, <span class="number">1</span>].min() - <span class="number">1</span>, x[:, <span class="number">1</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">grid_x = np.meshgrid(np.arange(l, r, h),</span><br><span class="line">	np.arange(b, t, v))</span><br><span class="line">flat_x = np.c_[grid_x[<span class="number">0</span>].ravel(), grid_x[<span class="number">1</span>].ravel()]</span><br><span class="line">flat_y = model.predict(flat_x)</span><br><span class="line">grid_y = flat_y.reshape(grid_x[<span class="number">0</span>].shape)</span><br><span class="line">mp.figure(<span class="string">'Mean Shift'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'Mean Shift'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.pcolormesh(grid_x[<span class="number">0</span>], grid_x[<span class="number">1</span>], grid_y, cmap=<span class="string">'gray'</span>)</span><br><span class="line">mp.scatter(x[:, <span class="number">0</span>], x[:, <span class="number">1</span>], c=model.labels_,</span><br><span class="line">	cmap=<span class="string">'brg'</span>, s=<span class="number">80</span>)</span><br><span class="line">mp.scatter(centers[:, <span class="number">0</span>], centers[:, <span class="number">1</span>],</span><br><span class="line">	marker=<span class="string">'+'</span>, c=<span class="string">'gold'</span>, s=<span class="number">1000</span>, linewidth=<span class="number">1</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<h2 id="凝聚层次聚类"><a href="#凝聚层次聚类" class="headerlink" title="凝聚层次聚类"></a>凝聚层次聚类</h2><p>首先假定每个样本都是一个独立的聚类，统计总聚类数，如果大于所要求的聚类数，就从每个样本出发，连接离它欧氏距离最近的样本，在扩大聚类的规模的同时减少聚类数，重复以上过程，直到总聚类数满足要求为止。</p>
<p>1)没有所谓聚类中心，适用于中心特性不明显的样本<br>2)无需事先给定聚类中心<br>3)在选择被凝聚样本的过程中，还可以分别按照距离优先和连续性优先两种方式选连接的样本。</p>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.cluster <span class="keyword">as</span> sc</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x = []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/multiple3.txt'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data = [float(substr) <span class="keyword">for</span> substr</span><br><span class="line">			<span class="keyword">in</span> line.split(<span class="string">','</span>)]</span><br><span class="line">		x.append(data)</span><br><span class="line">x = np.array(x)</span><br><span class="line"><span class="comment"># 凝聚层次聚类器</span></span><br><span class="line">model = sc.AgglomerativeClustering(n_clusters=<span class="number">4</span>)</span><br><span class="line">model.fit(x)</span><br><span class="line">mp.figure(<span class="string">'Agglomerative'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'Agglomerative'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.scatter(x[:, <span class="number">0</span>], x[:, <span class="number">1</span>], c=model.labels_,</span><br><span class="line">	cmap=<span class="string">'brg'</span>, s=<span class="number">80</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.cluster <span class="keyword">as</span> sc</span><br><span class="line"><span class="keyword">import</span> sklearn.neighbors <span class="keyword">as</span> sn</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">n_samples=<span class="number">500</span></span><br><span class="line">t = <span class="number">2.5</span> * np.pi * (<span class="number">1</span> + <span class="number">2</span> * np.random.rand(</span><br><span class="line">	n_samples, <span class="number">1</span>))</span><br><span class="line">x = <span class="number">0.05</span> * t * np.cos(t)</span><br><span class="line">y = <span class="number">0.05</span> * t * np.sin(t)</span><br><span class="line">n = <span class="number">0.05</span> * np.random.rand(n_samples, <span class="number">2</span>)</span><br><span class="line">x = np.hstack((x, y)) + n</span><br><span class="line"><span class="comment"># 无连续性凝聚层次聚类</span></span><br><span class="line">model = sc.AgglomerativeClustering(</span><br><span class="line">	linkage=<span class="string">'average'</span>, n_clusters=<span class="number">3</span>)</span><br><span class="line">y1 = model.fit_predict(x)</span><br><span class="line"><span class="comment"># 有连续性凝聚层次聚类</span></span><br><span class="line">nb = sn.kneighbors_graph(x, <span class="number">10</span>,</span><br><span class="line">	include_self=<span class="literal">False</span>)</span><br><span class="line">model = sc.AgglomerativeClustering(</span><br><span class="line">	linkage=<span class="string">'average'</span>, n_clusters=<span class="number">3</span>,</span><br><span class="line">	connectivity=nb)</span><br><span class="line">y2 = model.fit_predict(x)</span><br><span class="line">mp.figure(<span class="string">'Nonconnectivity'</span>,</span><br><span class="line">	facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'Nonconnectivity'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.grid(linestyle=<span class="string">':'</span>)</span><br><span class="line">mp.scatter(x[:, <span class="number">0</span>], x[:, <span class="number">1</span>], c=y1, cmap=<span class="string">'brg'</span>,</span><br><span class="line">	s=<span class="number">80</span>, alpha=<span class="number">0.5</span>)</span><br><span class="line">mp.figure(<span class="string">'Connectivity'</span>,</span><br><span class="line">	facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'Connectivity'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.grid(linestyle=<span class="string">':'</span>)</span><br><span class="line">mp.scatter(x[:, <span class="number">0</span>], x[:, <span class="number">1</span>], c=y2, cmap=<span class="string">'brg'</span>,</span><br><span class="line">	s=<span class="number">80</span>, alpha=<span class="number">0.5</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<h2 id="聚类的评价指标"><a href="#聚类的评价指标" class="headerlink" title="聚类的评价指标"></a>聚类的评价指标</h2><p>内密外疏<br>对于每个样本计算内部距离a和外部距离b，得到该样本的轮廓系数s=(b-a)/max(a, b)，对所有样本的轮廓系数取平均值，即为整个样本空间的轮廓系数S=ave(s)。<br>内部距离a: 一个样本与同聚类其它样本的平均欧氏距离<br>外部距离b: 一个样本与离其聚类最近的另一个聚类中所有样本的平均欧氏距离。<br><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.cluster <span class="keyword">as</span> sc</span><br><span class="line"><span class="keyword">import</span> sklearn.metrics <span class="keyword">as</span> sm</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x = []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/multiple3.txt'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data = [float(substr) <span class="keyword">for</span> substr</span><br><span class="line">			<span class="keyword">in</span> line.split(<span class="string">','</span>)]</span><br><span class="line">		x.append(data)</span><br><span class="line">x = np.array(x)</span><br><span class="line"><span class="comment"># K均值聚类器</span></span><br><span class="line">model = sc.KMeans(n_clusters=<span class="number">4</span>)</span><br><span class="line">model.fit(x)</span><br><span class="line">centers = model.cluster_centers_ <span class="comment"># 聚类中心</span></span><br><span class="line"><span class="comment"># 轮廓系数得分</span></span><br><span class="line">s = sm.silhouette_score(x, model.labels_,</span><br><span class="line">	sample_size=len(x), metric=<span class="string">'euclidean'</span>)</span><br><span class="line">print(s)</span><br><span class="line">l, r, h = x[:, <span class="number">0</span>].min() - <span class="number">1</span>, x[:, <span class="number">0</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">b, t, v = x[:, <span class="number">1</span>].min() - <span class="number">1</span>, x[:, <span class="number">1</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">grid_x = np.meshgrid(np.arange(l, r, h),</span><br><span class="line">	np.arange(b, t, v))</span><br><span class="line">flat_x = np.c_[grid_x[<span class="number">0</span>].ravel(), grid_x[<span class="number">1</span>].ravel()]</span><br><span class="line">flat_y = model.predict(flat_x)</span><br><span class="line">grid_y = flat_y.reshape(grid_x[<span class="number">0</span>].shape)</span><br><span class="line">mp.figure(<span class="string">'K-Means'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'K-Means'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.pcolormesh(grid_x[<span class="number">0</span>], grid_x[<span class="number">1</span>], grid_y, cmap=<span class="string">'gray'</span>)</span><br><span class="line">mp.scatter(x[:, <span class="number">0</span>], x[:, <span class="number">1</span>], c=model.labels_,</span><br><span class="line">	cmap=<span class="string">'brg'</span>, s=<span class="number">80</span>)</span><br><span class="line">mp.scatter(centers[:, <span class="number">0</span>], centers[:, <span class="number">1</span>],</span><br><span class="line">	marker=<span class="string">'+'</span>, c=<span class="string">'gold'</span>, s=<span class="number">1000</span>, linewidth=<span class="number">1</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure></p>
<h2 id="噪声密度聚类"><a href="#噪声密度聚类" class="headerlink" title="噪声密度聚类"></a>噪声密度聚类</h2><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.cluster <span class="keyword">as</span> sc</span><br><span class="line"><span class="keyword">import</span> sklearn.metrics <span class="keyword">as</span> sm</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x = []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/perf.txt'</span>, <span class="string">'r'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data = [float(substr) <span class="keyword">for</span> substr</span><br><span class="line">			<span class="keyword">in</span> line.split(<span class="string">','</span>)]</span><br><span class="line">		x.append(data)</span><br><span class="line">x = np.array(x)</span><br><span class="line">epsilons, scores, models = \</span><br><span class="line">    np.linspace(<span class="number">0.3</span>, <span class="number">1.2</span>, <span class="number">10</span>), [], []</span><br><span class="line"><span class="keyword">for</span> epsilon <span class="keyword">in</span> epsilons:</span><br><span class="line">	<span class="comment"># DBSCAN(噪声密度)聚类器</span></span><br><span class="line">	model = sc.DBSCAN(eps=epsilon,</span><br><span class="line">		min_samples=<span class="number">5</span>)</span><br><span class="line">	model.fit(x)</span><br><span class="line">	score = sm.silhouette_score(</span><br><span class="line">		x, model.labels_, sample_size=len(x),</span><br><span class="line">		metric=<span class="string">'euclidean'</span>)</span><br><span class="line">	scores.append(score)</span><br><span class="line">	models.append(model)</span><br><span class="line">scores = np.array(scores)</span><br><span class="line">best_index = scores.argmax()</span><br><span class="line">best_epsilon = epsilons[best_index]</span><br><span class="line">print(best_epsilon)</span><br><span class="line">best_score = scores[best_index]</span><br><span class="line">print(best_score)</span><br><span class="line">best_model = models[best_index]</span><br><span class="line">pred_y = best_model.labels_</span><br><span class="line">core_mask = np.zeros(len(x), dtype=bool)</span><br><span class="line">core_mask[</span><br><span class="line">	best_model.core_sample_indices_] = <span class="literal">True</span></span><br><span class="line">offset_mask = pred_y == <span class="number">-1</span></span><br><span class="line">periphery_mask = ~(core_mask | offset_mask)</span><br><span class="line">mp.figure(<span class="string">'DBSCAN'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'DBSCAN'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.grid(linestyle=<span class="string">':'</span>)</span><br><span class="line">labels = set(pred_y)</span><br><span class="line">cs = mp.get_cmap(<span class="string">'brg'</span>, len(labels))(</span><br><span class="line">	range(len(labels)))</span><br><span class="line">mp.scatter(x[core_mask][:, <span class="number">0</span>],</span><br><span class="line">	x[core_mask][:, <span class="number">1</span>],</span><br><span class="line">	c=cs[pred_y[core_mask]],</span><br><span class="line">	s=<span class="number">80</span>, label=<span class="string">'Core'</span>)</span><br><span class="line">mp.scatter(x[periphery_mask][:, <span class="number">0</span>],</span><br><span class="line">	x[periphery_mask][:, <span class="number">1</span>],</span><br><span class="line">	edgecolor=cs[pred_y[periphery_mask]],</span><br><span class="line">	facecolor=<span class="string">'none'</span>,</span><br><span class="line">	s=<span class="number">80</span>, label=<span class="string">'Periphery'</span>)</span><br><span class="line">mp.scatter(x[offset_mask][:, <span class="number">0</span>],</span><br><span class="line">	x[offset_mask][:, <span class="number">1</span>],</span><br><span class="line">	c=cs[pred_y[offset_mask]],</span><br><span class="line">	marker=<span class="string">'x'</span>,</span><br><span class="line">	s=<span class="number">80</span>, label=<span class="string">'Offset'</span>)</span><br><span class="line">mp.legend()</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<h2 id="最近邻"><a href="#最近邻" class="headerlink" title="最近邻"></a>最近邻</h2><h2 id="代码：knnc-py、knnr-py"><a href="#代码：knnc-py、knnr-py" class="headerlink" title="代码：knnc.py、knnr.py"></a>代码：knnc.py、knnr.py</h2><p>回归：线性、岭、多项式、决策树、SVM、KNN<br>R2得分<br>分类：逻辑、朴素贝叶斯、决策树、SVM、KNN<br>F1得分<br>聚类：K均值、均值漂移、凝聚层次、DBSCAN</p>
<h2 id="轮廓系数"><a href="#轮廓系数" class="headerlink" title="轮廓系数"></a>轮廓系数</h2>
      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/AI进阶/" rel="tag"># AI进阶</a>
          
            <a href="/tags/机器学习/" rel="tag"># 机器学习</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/02/22/ml/分类/" rel="next" title="机器学习-分类问题">
                <i class="fa fa-chevron-left"></i> 机器学习-分类问题
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/04/11/ml/推荐系统/" rel="prev" title="机器学习-推荐系统">
                机器学习-推荐系统 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.JPG" alt="任成">
            
              <p class="site-author-name" itemprop="name">任成</p>
              <div class="site-description motion-element" itemprop="description"></div>
          </div>

          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0NvZGVyQ3VydmU=" title="GitHub &rarr; https://github.com/CoderCurve"><i class="fa fa-fw fa-github"></i>GitHub</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="bWFpbHRvOnJlbmNoZW5nMTFAaWNsb3VkLmNvbQ==" title="E-Mail &rarr; mailto:rencheng11@icloud.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</span>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#概述"><span class="nav-number">1.</span> <span class="nav-text">概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#量化相似度"><span class="nav-number">2.</span> <span class="nav-text">量化相似度</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#欧式距离"><span class="nav-number">2.1.</span> <span class="nav-text">欧式距离</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#K均值聚类"><span class="nav-number">3.</span> <span class="nav-text">K均值聚类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#均值漂移聚类"><span class="nav-number">4.</span> <span class="nav-text">均值漂移聚类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#凝聚层次聚类"><span class="nav-number">5.</span> <span class="nav-text">凝聚层次聚类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#聚类的评价指标"><span class="nav-number">6.</span> <span class="nav-text">聚类的评价指标</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#噪声密度聚类"><span class="nav-number">7.</span> <span class="nav-text">噪声密度聚类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#最近邻"><span class="nav-number">8.</span> <span class="nav-text">最近邻</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#代码：knnc-py、knnr-py"><span class="nav-number">9.</span> <span class="nav-text">代码：knnc.py、knnr.py</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#轮廓系数"><span class="nav-number">10.</span> <span class="nav-text">轮廓系数</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">  <span class="exturl" data-url="aHR0cDovL3d3dy5iZWlhbi5taWl0Lmdvdi5jbg==">京ICP备18001214号 </span>&copy; 2014 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">任成</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
    <span title="站点总字数">277k</span>
  

  
</div>









        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/utils.js?v=7.1.2"></script>

  <script src="/js/motion.js?v=7.1.2"></script>



  
  


  <script src="/js/affix.js?v=7.1.2"></script>

  <script src="/js/schemes/pisces.js?v=7.1.2"></script>



  
  <script src="/js/scrollspy.js?v=7.1.2"></script>
<script src="/js/post-details.js?v=7.1.2"></script>



  


  <script src="/js/next-boot.js?v=7.1.2"></script>


  

  
  <script src="/js/exturl.js?v=7.1.2"></script>


  

  


  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
  

  
  

  
    
      <script type="text/x-mathjax-config">
  

  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$', '$'], ['\\(', '\\)'] ],
      processEscapes: true,
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      
      equationNumbers: {
        autoNumber: 'AMS'
      }
    }
  });
  MathJax.Hub.Register.StartupHook('TeX Jax Ready', function() {
    MathJax.InputJax.TeX.prefilterHooks.Add(function(data) {
      if (data.display) {
        var next = data.script.nextSibling;
        while (next && next.nodeName.toLowerCase() === '#text') { next = next.nextSibling }
        if (next && next.nodeName.toLowerCase() === 'br') { next.parentNode.removeChild(next) }
      }
    });
  });
</script>

<script type="text/x-mathjax-config">
  MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for (i = 0; i < all.length; i += 1) {
      document.getElementById(all[i].inputID + '-Frame').parentNode.className += ' has-jax';
    }
  });
</script>
<script src="//cdn.jsdelivr.net/npm/mathjax@2/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

    
  


  

  
<script>
if ($('body').find('pre.mermaid').length) {
  $.ajax({
    type: 'GET',
    url: '//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js',
    dataType: 'script',
    cache: true,
    success: function() {
      mermaid.initialize({
        theme: 'forest',
        logLevel: 3,
        flowchart: { curve: 'linear' },
        gantt: { axisFormat: '%m/%d/%Y' },
        sequence: { actorMargin: 50 }
      });
    }
  });
}
</script>


  

  

  

  

  

  

  

  

  

</body>
</html>
